package com.ibl.rover.lite.client.Sync.Process;

import java.io.FileOutputStream;

import org.apache.http.conn.ConnectTimeoutException;
 
import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Sync.Parser.SyncDataUpdateObserver;
import com.ibl.rover.lite.client.Sync.Parser.SyncXMLParser;
import com.ibl.rover.lite.client.constants.RoverConstants;
import com.ibl.rover.lite.client.constants.RoverConstants.ServerErrCode;
import com.ibl.rover.lite.client.constants.RoverConstants.SyncProgress;
import com.mobile.sync.client.Sync.impl.HTTPSyncImpl;
import com.mobile.sync.client.impl.AbstractBean;
import com.mobile.sync.client.impl.RequestBean;
import com.mobile.sync.client.impl.ResponseBean;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public abstract class SyncronizationProcess extends
		AsyncTask<AbstractBean, Integer, AbstractBean> {

	protected ProgressDialog progress;
	private Context context;
	private ApplicationContext roverContext;
	private Logger logger = Logger.getLogger();

	public SyncronizationProcess(
			Context context,ApplicationContext roverContext) {
		this.context = context;
		this.roverContext = roverContext;
		progress = new ProgressDialog(context);
	}

	@Override
	protected void onPreExecute() {
		String progressMsg = context.getString(R.string.server_communication);
		progress.setMessage(progressMsg);
		progress.show();
	}

	@Override
	protected AbstractBean doInBackground(AbstractBean... params) {
		ResponseBean responseBean = null;
		try {
 			HTTPSyncImpl syncImpl = roverContext.getHttpSyncImpl();
			responseBean = (ResponseBean) syncImpl.send(params[0]);
			// FileOutputStream outputStream =
			// ssaContext.openFileOutput(SSAConstants.SYNC_XML_PATH,
			// Context.MODE_WORLD_READABLE);
			// responseMsg = (ResponseMessage)
			// transportAgent.send(params[0],outputStream);

			logger.log("[Http Response Code : "
					+ responseBean.getServerResponseCode() + "]");
			logger.log("[Server Response Code : "
					+ responseBean.getMessageCode() + "]");
			if (ResponseBean.HTTP_OK == responseBean.getServerResponseCode()
					&& ServerErrCode.SUCCESS == responseBean.getMessageCode()) {
				publishProgress(SyncProgress.SYNC_SERVER_SUCCESS);

				if (null != responseBean.getDataChunk()) {
					// if (roverContext.getAppParams().isLogHttpMessage()) {
					// // String responseStr = new
					// // String(responseMsg.getBodyChunk());
					// // logger.log("[Response Message : " + responseStr +
					// // "]");
					// }

					FileOutputStream syncXml = roverContext.openFileOutput(
							RoverConstants.SYNC_XML_PATH,
							Context.MODE_WORLD_READABLE);
					syncXml.write(responseBean.getDataChunk());
					syncXml.close();
					SyncXMLParser syncXmlParser = new SyncXMLParser(context,
							Integer.parseInt(roverContext.getAppParams()
									.getMaxListlength()),
							new SyncDataUpdateObserver(roverContext, this),
							RoverConstants.SYNC_XML_PATH);
					syncXmlParser.parse();
					context.deleteFile(RoverConstants.SYNC_XML_PATH);
				}
			}

		} catch (ConnectTimeoutException ex) {
			logger.logException(
					"[Exception occured in TransportTask.doInBack..]", ex);
			if (null == responseBean) {
				responseBean = new ResponseBean();
			}
			responseBean.setMessageCode(ResponseBean.CONNECTION_TIME_OUT);
			responseBean.setMessage(ex.getMessage());
		} catch (Exception ex) {
			logger.logException(
					"[Exception occured in TransportTask.doInBack..]", ex);
			if (null == responseBean) {
				responseBean = new ResponseBean();
			}
			responseBean.setMessageCode(ResponseBean.GENERIC_ERROR);
			responseBean.setMessage(ex.getMessage());
			ex.printStackTrace();
		}
		return responseBean;
	}

	@Override
	protected void onPostExecute(AbstractBean result) {
		if (this.progress.isShowing()) {
			this.progress.dismiss();
		}
		 onResponseComplete(result);
	}

	public void doProgress(final int progress) {
		publishProgress(progress);
	}
	
	public abstract void onResponseComplete(AbstractBean response);
}
